package com.example.yuanboot.common.config.datasource;

import java.util.Optional;

/**
 * 数据源操作，读写分离
 *
 * @author csp 2021-08-22
 */
public class DataSourceHolder {
    /**
     * 适用于主从库切换，只有主数据库宕后切到从数据库
     */
    private static ThreadLocal<String> dataSource = new ThreadLocal<>();

    /**
     * To switch DataSource
     *
     * @param key the key
     */
    public static synchronized void setDataSourceKey(String key) {
        dataSource.set(key);
    }

    /**
     * Get current DataSource
     *
     * @return data source key
     */
    public static String getDataSourceKey() {
        return Optional.ofNullable(dataSource.get()).orElse("master");
    }
    /**
     * To set DataSource as default
     */
    public static void clearDataSourceKey() {
        dataSource.remove();
    }

}
